// 页面加载时，自动执行
$(document).ready(function() {

	// 加载项目类型数据
	queryProjectInfo();
	
	// demo
	pageInitDemo();
	
});

// 查询项目类型数据
function queryProjectInfo(){

    // Ajax查询项目类型管理
    var url = $("#basepath").val() + "/projecttype/queryProjectTypeByAll";
	console.log("查询项目类型");
	$.ajax({
        type: "POST", //请求类型 get , put, delete
        url: url, // 请求地址
        data: JSON.stringify({"demo": "demo1"}), // data 请求参数
        dataType: "json",  // 返回数据类型
        contentType: "application/json;charset=utf-8",
        success: function(data, textStatus, jqXHR) {
			pageInitDemo(data.listdata);
        }
    });

}

// jqGrid Demo
function pageInit(mydata){
  jQuery("#list4").jqGrid(
      {
        datatype : "local",
        height : 250,
        colNames : [ 'Inv No', 'Date', 'Client', 'Amount', 'Tax','Total', 'Notes' ],
        colModel : [ 
                     {name : 'id',index : 'id',width : 60,sorttype : "int"}, 
                     {name : 'invdate',index : 'invdate',width : 90,sorttype : "date"}, 
                     {name : 'name',index : 'name',width : 100}, 
                     {name : 'amount',index : 'amount',width : 80,align : "right",sorttype : "float"}, 
                     {name : 'tax',index : 'tax',width : 80,align : "right",sorttype : "float"}, 
                     {name : 'total',index : 'total',width : 80,align : "right",sorttype : "float"}, 
                     {name : 'note',index : 'note',width : 150,sortable : false} 
                   ],
        multiselect : true,
        caption : "Manipulating Array Data"
      });
      /*
      
  var mydata = [ 
                 {id : "1",invdate : "2021-10-01",name : "test",note : "note",amount : "200.00",tax : "10.00",total : "210.00"}, 
                 {id : "2",invdate : "2021-10-02",name : "test2",note : "note2",amount : "300.00",tax : "20.00",total : "320.00"}, 
                 {id : "3",invdate : "2021-09-01",name : "test3",note : "note3",amount : "400.00",tax : "30.00",total : "430.00"}, 
                 {id : "4",invdate : "2021-10-04",name : "test",note : "note",amount : "200.00",tax : "10.00",total : "210.00"}, 
                 {id : "5",invdate : "2021-10-05",name : "test2",note : "note2",amount : "300.00",tax : "20.00",total : "320.00"}, 
                 {id : "6",invdate : "2021-09-06",name : "test3",note : "note3",amount : "400.00",tax : "30.00",total : "430.00"}, 
                 {id : "7",invdate : "2021-10-04",name : "test",note : "note",amount : "200.00",tax : "10.00",total : "210.00"}, 
                 {id : "8",invdate : "2021-10-03",name : "test2",note : "note2",amount : "300.00",tax : "20.00",total : "320.00"}, 
                 {id : "9",invdate : "2021-09-01",name : "test3",note : "note3",amount : "400.00",tax : "30.00",total : "430.00"} 
               ];
               
              */ 
  for ( var i = 0; i <= mydata.length; i++){
    jQuery("#list4").jqGrid('addRowData', i + 1, mydata[i]);
  }
}
			


// 时间格式转换
function getYMDHMS (timestamp) {
      let time = new Date(timestamp)
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      let date = time.getDate()
      let hours = time.getHours()
      let minute = time.getMinutes()
      let second = time.getSeconds()

      if (month < 10) { month = '0' + month }
      if (date < 10) { date = '0' + date }
      if (hours < 10) { hours = '0' + hours }
      if (minute < 10) { minute = '0' + minute }
      if (second < 10) { second = '0' + second }
      return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
////////////////////////////////////////////////////////////////////

// 查询项目类型
function queryProjectType(){
	var url = $("#basepath").val() + "/demand/listProjectTypeName";
	console.log("查询项目类型");
	$.ajax({
        type: "POST", //请求类型 get , put, delete
        url: url, // 请求地址
        data: {}, // data 请求参数
        dataType: "json",  // 返回数据类型
        contentType: "application/json;charset=utf-8",
        success: function(da, textStatus, jqXHR) {
        	var arr = da.projectType;
        	for(var i = 0; i < arr.length; i++){
        			// $(this).css("color", "red");
        			// var button = '<button name="projectName" type="button" style="color: red" class="layui-btn" value="' + arr[i].projectTypeId + '">' + arr[i].projectTypeName + '</button>';
        			// $("#projectType").append(button);
        			// 赋值
					// $("#projectTypeId").val(arr[i].projectTypeId);
					// $("#projectTypeName").val(arr[i].projectTypeName);
        			var button = '<button name="projectName" type="button" class="layui-btn" value="' + arr[i].projectTypeId + '">' + arr[i].projectTypeName + '</button>';
        			$("#projectType").append(button);
        	}
        	// 注册点击事件
        	buttonEvent();
        }
    });
}

// 项目类型点击事件
function buttonEvent(){
	// $(document).ready(function(){
		$("[name='projectName']").click(function(){
			$(this).siblings().css("color", "blue");
			$(this).css("color", "red");
			$(this).css("background-color", "green");
			
			// 赋值
			$("#projectTypeId").val($(this).val());
			$("#projectTypeName").val($(this).html());
		});
	// });
}

// 查询需求列表 
function queryDemand() {
	var url = $("#basepath").val() + "/demand/listDemandByAll";

	$.ajax({
        type: "post", 
        url: url, 
        data: JSON.stringify({}), 
        dataType: "json",  
        contentType: "application/json;charset=utf-8",
        success: function(data) {
        	console.log("data::: " + data);
        	console.log("data-code::: " + data.code);
        	console.log("data-msg::: " + data.msg);
        	console.log("data-dataList::: " + data.dataList);
        	console.log("data-demandId::: " + data.dataList);
        	var arr = data.dataList;
        	for(var i = 0; i < arr.length; i++) {
        	
        		console.log("data-demandId::: " + arr[i].demandId);
        		$("#demandList").append('<div>');
        		$("#demandList").append('<div class="form-group img-rounded" style="float: left">');
        		$("#demandList").append('<img src="https://tse3-mm.cn.bing.net/th/id/OIP.0HW_9vVbKZQBqamThA0R9gAAAA?pid=ImgDet&rs=1"/>');
        		$("#demandList").append('</div>');

        		$("#demandList").append('<div class="form-group" style="float: left"><div>');
        		console.log("addr::　" + $("#basePath").val());
        		$("#demandList").append('<a href="' + $("#basePath").val()  + '/demand/demandDetialPage?demandId=' + arr[i].demandId + '">' + arr[i].demandProjectName + '</a>');
        		$("#demandList").append('<span>' + arr[i].budgetAmount + '</span> </div>');
        		$("#demandList").append('<div><span>项目</span> <span>' + arr[i].projectTypeName + '</span> <span>工期' + arr[i].duration + '天</span></div> ');
        		$("#demandList").append('<div> <span>技能要求: ' + arr[i].technicalName + '</span>  <span>参与4人</span> <span>发布于' + getYMDHMS(arr[i].createTime) + '</span> </div> </div> ');
        		$("#demandList").append('</div>');
        		$("#demandList").append('<hr/>');
        	}
        	
        	
        }
    });

}


// 技能要求
function queryTechnical(){
	var url = $("#basepath").val() + "/demand/listTechnical";
	$.ajax({
        type: "POST", //请求类型 get , put, delete
        url: url, // 请求地址
        data: {}, // data 请求参数
        dataType: "json",  // 返回数据类型
        contentType: "application/json;charset=utf-8",
        success: function(da, textStatus, jqXHR) {
        	var arr = da.technical;
        	for(var i = 0; i < arr.length; i++){
        		console.log("project:technicalId::" + arr[i].technicalId);
        		console.log("project:technicalName::" + arr[i].technicalName);
        		var checkboxstr = '<input type="checkbox" name="technicalName" title="' + arr[i].technicalName + '" value="' + arr[i].technicalName + '">';
        		$("#technicalId").append(checkboxstr);
        	}
        	
        	// layui框架，新加的表单元素一定要重新渲染
			var form = layui.form;
        	form.render('checkbox');
        }
    });
}






// 联动菜单 省
layui.use('form', function() {
    console.log("hello demandmain...");
    var form = layui.form;
    var url = $("#basepath").val() + "/linkage/provinces";
    console.log("请求地址::: " + url);
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify({
            "flag": "1"
        }),
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success: function(ajaxdata, textStatus, jqXHR) {
            var option = '';
            console.log("code::: " + ajaxdata.code);
            if (ajaxdata.code == "0000") {
                for (var i = 0; i < ajaxdata.data.length; i++) { //循环获取返回值，并组装成html代码
                    option += " <option value='" + ajaxdata.data[i].provinceid + "'>" + ajaxdata.data[i].province + "</option>";
                }
            } else {
                var option = '<option value="0">请选择</option>';
            }
            $("#provincesid").html("");
            $("#provincesid").html(option);
            form.render('select');
        }
    });
});

/**
 * [城市下拉列表]
 * @return {[type]} [description]
 */
layui.use('form', function() {
    var form = layui.form;
    form.on('select(provinces)', function(provincedata) {
        var url = $("#basepath").val() + "/linkage/cities";
        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify({ "provinceid": provincedata.value}),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function(ajaxdata, textStatus, jqXHR) {
                var option = '';
                console.log("code::: " + ajaxdata.code);
                if (ajaxdata.code == "0000") {
                    for (var i = 0; i < ajaxdata.data.length; i++) { //循环获取返回值，并组装成html代码
                        option += " <option value='" + ajaxdata.data[i].cityid + "'>" + ajaxdata.data[i].city + "</option>";
                    }
                } else {
                    var option = '<option value="0">请选择</option>';
                }
                // var option1 = '<option value="0">请选择</option>';
                $("#citiesid").html("");
                $("#citiesid").html(option);
                form.render('select');
            }
        });
    });
});


// 工期单位选择
function durationUnit() {
	$("[name='durationUnitName']").click(function(){
		$(this).siblings().css("color", "blue");
		$(this).css("color", "red");
		$(this).css("background-color", "green");
			
		console.log("工期单::: " + $(this).val());
		// 赋值
		$("#durationUnit").val($(this).val());
		// $("#projectTypeName").val($(this).html());
	});
	
	// 设置默认值
	$("#durationUnit").val($("#durationUnitDay").val());
	$("#durationUnitDay").siblings().css("color", "blue");
	$("#durationUnitDay").css("color", "red");
	$("#durationUnitDay").css("background-color", "green");

}



layui.use(['form', 'layedit', 'laydate'], function() {
    var form = layui.form,
        layer = layui.layer,
        layedit = layui.layedit,
        laydate = layui.laydate;

    //日期
    laydate.render({
        elem: '#date'
    });
    laydate.render({
        elem: '#date1'
    });

    //创建一个编辑器
    var editIndex = layedit.build('LAY_demo_editor');

    //自定义验证规则
    form.verify({
    /**
        title: function(value) {
            if (value.length < 5) {
                return '标题至少得5个字符啊';
            }
        },
        pass: [
            /^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
        ],
        content: function(value) {
            layedit.sync(editIndex);
        }
     */
    });

    //监听指定开关
    form.on('switch(switchTest)', function(data) {
        layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
            offset: '6px'
        });
        layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
    });

    //监听提交-保存到草稿箱
    form.on('submit(saveDraftBox)', function(data) {
        // layui赋值方式
    	form.val('demandForm', {
      		"demandFlag": "0" // "name": "value" 设置需求标识
    	});

        layer.alert(JSON.stringify(data.field), {
            title: '最终的提交信息'
        })
        return true;
    });
    
    //监听提交-立即发布
    form.on('submit(publish)', function(data) {
    	$("#demandFlag").val("1");
        layer.alert(JSON.stringify(data.field), {
            title: '最终的提交信息'
        })
        return true;
    });
});

// Demo 表格
function pageInitDemo(data){
  jQuery("#listDemo").jqGrid(
      {
        datatype : "local",
        height : 250,
        colNames : [ '序号', '主键ID', '项目类型名称', '创建时间', '修改时间', '操作' ],
        colModel : [ 
                     {name : 'id', index : 'id',width : 60, sorttype : "int"}, 
                     {name : 'pkId', index : 'pkId',width : 60, hidden: true }, 
                     {name : 'projectTypeName', index : 'projectTypeName', width: 90}, 
                     {name : 'createTime', index : 'createTime',width : 180, formatter: function(cellvalue, options, rowObject){return getYMDHMS(cellvalue)}},
                     {name : 'updateTime', index : 'updateTime',width : 180,  formatter: function(cellvalue, options, rowObject){return getYMDHMS(cellvalue)}},
                     {name : 'operation', index : 'operation',width : 160, formatter: function(cellvalue, options, rowObject){return memuType()}},
                   ],
        multiselect : true,
        caption : "项目类型管理"
      });

  var mydata = [];
  mydata = data;
  for ( var i = 0; i <= mydata.length; i++){
    jQuery("#listDemo").jqGrid('addRowData', i + 1, data[i]);
  }
}

function timeFormat(cellvalue, options, rowObject) {
	return getYMDHMS(cellvalue);
}

function memuType() {
	return '<button type="button"> 百搭按钮</button>';
}

// 添加项目类型
function addProjectType() {

	//页面层
	
	/**
	var ids=$('#listDemo').jqGrid('getGridParam','selarrrow');
	alert("ids::: " + ids);
	alert("ids-length::: " + ids.length);
	alert("ids-[]::: " + ids[0]);
	
	var rowData = $("#listDemo").jqGrid('getRowData',rowId);
	alert("rowData:id::: " + rowData.projectTypeId);
	alert("rowData:name::: " + rowData.projectTypeName);
	*/
	
	console.log("addProjectType:::");
	
	var url = $("#basepath").val() + "/projecttype/projectTypeAdd";

	layer.open({
      type: 2,
      title: '添加项目类型',
      shadeClose: true,
      shade: false,
      maxmin: true, //开启最大化最小化按钮
      area: ['400px', '250px'],
      content: url
    });

}


// 修改项目类型
function editProjectType() {

	var ids=$('#listDemo').jqGrid('getGridParam','selarrrow');
	console.log("选择的行数-ids::: " + ids);
	if (ids.length != 1) {
		layer.msg("请选择一条数据");
		return;
	}
	
	var rowData = $("#listDemo").jqGrid('getRowData', ids[0]);
	console.log("rowData:id::: " + rowData.pkId);
	console.log("rowData:name::: " + rowData.projectTypeName);
	
	var url = $("#basepath").val() + "/projecttype/modifyProjecttypePage?pkId=" + rowData.pkId + "&projectTypeName=" + rowData.projectTypeName;

	layer.open({
      type: 2,
      title: '修改项目类型',
      shadeClose: true,
      shade: false,
      maxmin: true, //开启最大化最小化按钮
      area: ['400px', '250px'],
      content: url
    });

}


// 删除项目类型
function delProjectType() {

	var ids=$('#listDemo').jqGrid('getGridParam','selarrrow');
	console.log("选择的行数-ids::: " + ids);
	if (ids.length < 1) {
		layer.msg("请选择到少一条数据");
		return;
	}
	
	// var rowData = $("#listDemo").jqGrid('getRowData', ids[0]);
	// console.log("rowData:id::: " + rowData.pkId);
	// console.log("rowData:name::: " + rowData.projectTypeName);
	
	var WData = [];
	for(var i=0;i<ids.length;i++){
		var rowData = $("#listDemo").jqGrid('getRowData', ids[i]);
		 console.log("rowData:id::: " + rowData.pkId);
		 console.log("rowData:name::: " + rowData.projectTypeName);
		 WData[i]=rowData.pkId;
	
	}
	
	// var url = $("#basepath").val() + "/projecttype/removeProjecttypePage?pkId=" + rowData.pkId + "&projectTypeName=" + rowData.projectTypeName;
	var url = $("#basepath").val() + "/projecttype/removeProjecttypePage?pkId=" + WData + "&projectTypeName=" + rowData.projectTypeName;
	
	layer.open({
      type: 2,
      title: '删除项目类型',
      shadeClose: true,
      shade: false,
      maxmin: true, //开启最大化最小化按钮
      area: ['400px', '250px'],
      content: url
    });
}




// 删除项目类型
function delMutilProjectType() {

	var ids=$('#listDemo').jqGrid('getGridParam','selarrrow');
	console.log("选择的行数-ids::: " + ids);
	if (ids.length < 1) {
		layer.msg("请选择到少一条数据");
		return;
	}
	
	// var rowData = $("#listDemo").jqGrid('getRowData', ids[0]);
	// console.log("rowData:id::: " + rowData.pkId);
	// console.log("rowData:name::: " + rowData.projectTypeName);
	
	// 遍历获取pkId
	var WData = [];
	for(var i=0;i<ids.length;i++){
		var rowData = $("#listDemo").jqGrid('getRowData', ids[i]);
		 console.log("rowData:id::: " + rowData.pkId);
		 console.log("rowData:name::: " + rowData.projectTypeName);
		 var obj = {};
		 obj.pkId = rowData.pkId;
		 obj.projectTypeName = rowData.projectTypeName;
		 WData[i] = obj;
	}
	// var sData = encode64(JSON.stringify(WData));
	var sData = base64Encode(JSON.stringify(WData));
	
	console.log("sData::: " + sData);
	
	var url = $("#basepath").val() + "/projecttype/removeProjecttypePage?pkId=" + sData;
	
	layer.open({
      type: 2,
      title: '删除项目类型',
      shadeClose: true,
      shade: false,
      maxmin: true, //开启最大化最小化按钮
      area: ['400px', '250px'],
      content: url
    });
}


